package com.cyy.common.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import com.cyy.common.config.interceptor.CorsInterceptor;
import com.cyy.common.config.interceptor.PageableInterceptor;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${file.uploadPath}")
    private String uploadPath;
    @Resource
    private CorsInterceptor corsInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 跨域拦截配置
        registry.addInterceptor(corsInterceptor).addPathPatterns("/**");
        // 请求Sa-Token校验拦截
        registry
                .addInterceptor(new SaInterceptor(handle -> {
                    if (StpUtil.isLogin()) {
                        // 剩余有效时间
                        long tokenTimeout = StpUtil.getTokenTimeout();
                        // 如果时间超过半天就不做处理，小于半天就进行一天的延期
                        if (tokenTimeout < 43200) {
                            StpUtil.renewTimeout(60 * 60 * 24);
                        }
                    }
                }))
                .addPathPatterns("/**")
                //swagger
                .excludePathPatterns("/favicon.ico", "/webjars/**", "/img.icons/**", "/swagger-resources/**", "/v3/api-docs/**", "/swagger-ui/**", "/doc.html", "/swagger-ui.html");
        // 分页拦截器
        registry.addInterceptor(new PageableInterceptor());
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 跨域配置
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                .allowedOriginPatterns("*")
                // 设置访问源请求头
                .allowedHeaders("*")
                // 设置允许的方法
                .allowedMethods("*")
                // 是否允许证书（cookies）
                .allowCredentials(true)
                // 跨域允许时间
                .maxAge(3600);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //文件上传路径映射
        registry.addResourceHandler("/document/upload/**").addResourceLocations("file:" + uploadPath);
    }
    
}
